<?php

namespace app\controller;

use app\BaseController;
use app\model\AdminModel;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\middleware\Check;
use think\response\Json;
use think\validate\ValidateRule;
use \Exception as E;
use \think\exception\ValidateException as VE;
/**
 * Class Order 管理端 统计类控制器
 * @package app\controller
 */
class Statistical extends BaseController
{
    protected $middleware = [Check::class];

    /**获取订单列表
     * @param Request $request
     * @return Json
     */
    public function orderList(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['start'] = $request->post('start');
            $input['end'] = $request->post('end');
            $input['limit'] = $request->post('limit');//每页显示数量
            $input['page'] = $request->post('page');//当前页
            // 参数校验
            $validate = Validate::rule([
                'limit' => ValidateRule::isRequire(null, '缺少参数'),
                'page' => ValidateRule::isRequire(null, '缺少参数'),
                'start' => function($value) {
                    return $value === null ? '缺少参数' : true;
                },
                'end' => function($value) {
                    return $value === null ? '缺少参数' : true;
                },
            ]);
            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            validate(['start' => 'date'])->check($input);
            validate(['end' => 'date'])->check($input);
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1],[1,2,3,4]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [];
            if ($adminInfo['type'] == 4 || $adminInfo['type'] == 3) {
                //判断上级类型
                $info = Db::table('eb_admin')->field('id,type')->where('id', $adminInfo['pid'])->find();
                if (!$info) return jsonFail('未找到数据');
                $adminInfo['id'] = $info['id'];
                $adminInfo['type'] = $info['type'];
            }
            switch ($adminInfo['type']) {
                case 1: // 超管
                    $field = 'id,order_no,total_price,delivery_price,floor_price,goods_price,company_price,operate_price,store_price,company_status,operate_status,status,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time,pay_type,send_status,dor_manager_status,box_status';
                    break;
                case 2: // 运营方
                    $map[] = ['operate_id', '=', $adminInfo['id']];
                    $field = 'id,order_no,company_price,total_price,delivery_price,floor_price,goods_price,operate_price,store_price,company_status,operate_status,status,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time,pay_type,send_status,dor_manager_status,box_status';
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            if ($input['start'] != '') $map[] = ['create_time', '>=', strtotime($input['start'])];
            if ($input['end'] != '') $map[] = ['create_time', '<=', strtotime($input['end'])];
            $table = Db::table('eb_order')->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Ve $e) {
            return jsonFail('非法的时间格式');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**订单划账明细
     * @param Request $request
     * @return Json
     */
    public function drawInfo(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['start'] = $request->post('start');//起始时间
            $input['end'] = $request->post('end');//结束时间
            $input['type'] = $request->post('type');// 划账类型
            // 参数校验
            $validate = Validate::rule([
                'start' => ValidateRule::isDate(null, '缺少参数'),
                'end' => ValidateRule::isDate(null, '缺少参数'),
                'type' => function($value) {
                    if ($value === null) {
                        return '缺少参数';
                    } else if (in_array($value, ['1','2','3','4','5'], true)) {
                        return true;
                    } else {
                        return '不合法参数';
                    }
                }
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1],[1,2,3,4]);
            if ($adminInfo instanceof Json) return $adminInfo;
            if ($adminInfo['type'] == 4 || $adminInfo['type'] == 3) {
                //判断上级类型
                $info = Db::table('eb_admin')->field('id,type')->where('id', $adminInfo['pid'])->find();
                if (!$info) return jsonFail('未找到数据');
                $adminInfo['id'] = $info['id'];
                $adminInfo['type'] = $info['type'];
            }
            $map = [
                ['o.status', 'in', [6,7]],
                ['is_pay', '=', 1]
            ];
            $table = Db::table('eb_order')->alias('o');
            switch ($adminInfo['type']) {
                case 1: // 超管
                    if ($input['type'] == 1) {
                        // 给运营商划账
                        $field = 'sum(total_price - company_price) as money,op.name as operate_name, op.bank_no as operate_bank_no,op.bank_name as operate_bank_name,o.operate_id as id';
                        $map[] = ['company_status', '=', 0];
                        $group = 'o.operate_id';
                        $table->join(['eb_admin' => 'op'], 'op.id = o.operate_id');
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                case 2: // 运营方
                    $map[] = ['company_status', '=', 1];
                    $map[] = ['o.operate_id', '=', $adminInfo['id']];
                    if ($input['type'] == 2) { // 给商户划账
                        $map[] = ['operate_status', '=', 0];
                        $field = 'sum(store_price) as money, s.shop_name, s.bank_no as bank_no,s.bank_address as bank_address,o.store_id as id';
                        $group = 'o.store_id';
                        $table->join(['eb_store' => 's'], 's.id = o.store_id');
                    } else if($input['type'] == 3) { // 给配送划账
                        $map[] = ['send_status', '=', 0];
                        $field = 'sum(floor_price) as money,u.name, u.bank_no,u.bank_name,(o.send_id) as id';
                        $group = 'o.send_id';
                        $table->join(['eb_user' => 'u'], 'u.id = o.send_id');
                    } else if($input['type'] == 4) { // 给楼管划账
                        // 获取每单划账费用
//                        Db::table('eb_school')
                        $map[] = ['dor_manager_status', '=', 0];
                        $field = 'count(*) as order_number,sr.name, sr.phone,(o.manag_id) as id,s.dor_manager_price,sum(s.dor_manager_price) as money';
                        $group = 'o.manag_id';
                        $table->join(['eb_school_role' => 'sr'], 'sr.id = o.manag_id');
                        $table->join(['eb_school' => 's'], 's.id = o.school_id');
                    } else if($input['type'] == 5) { // 给装箱划账
                        $map[] = ['box_status', '=', 0];
                        $field = 'count(*) as order_number,sr.name, sr.phone,(o.Boxing_id) as id,s.box_price,sum(s.box_price) as money';
                        $group = 'o.Boxing_id';
                        $table->join(['eb_school_role' => 'sr'], 'sr.id = o.Boxing_id');
                        $table->join(['eb_school' => 's'], 's.id = o.school_id');
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            if ($input['start'] != '') $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            if ($input['end'] != '') $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            $info = $table->field($field)->where($map)->group($group)->select();
            if ($info == []) return jsonFail('没有可划账的订单');
            // 整理数据
            return jsonSuccess('获取成功', ['info' => $info]);
        } catch (E $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }

    /**订单划账
     * @param Request $request
     * @return Json
     */
    public function draw(Request $request)
    {
        $flag = false;
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['type'] = $request->post('type');// 划账类型
            $input['data'] = $request->post('data');// 更改记录
            $input['start'] = $request->post('start');//
            $input['end'] = $request->post('end');//
            // 参数校验
            $validate = Validate::rule([
                'type' => ValidateRule::isRequire(null, '缺少参数'),
                'data' => ValidateRule::isRequire(null, '缺少参数'),
                'start' => ValidateRule::isRequire(null, '缺少参数')->dateFormat('Y-m-d H:i:s', '非法参数'),
                'end' => ValidateRule::isRequire(null, '缺少参数')->dateFormat('Y-m-d H:i:s', '非法参数'),
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            $log = [];
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1],[1,2,3,4]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $log['operate_id'] = $adminInfo['id'];
            $log['pid'] = 0;
            $log['name'] = $adminInfo['name'];
            $log['draw_time'] = $input['start'] . '至' . $input['end'];
            $log['create_time'] = time();
            if ($adminInfo['type'] == 4 || $adminInfo['type'] == 3) {
                //判断上级类型
                $info = Db::table('eb_admin')->field('id,type')->where('id', $adminInfo['pid'])->find();
                if (!$info) return jsonFail('未找到数据');
                $adminInfo['id'] = $info['id'];
                $adminInfo['type'] = $info['type'];
                $log['pid'] = $adminInfo['id'];
            }
            $map = [
                ['o.status', 'in', [6,7]],
                ['o.is_pay', '=', 1],
                ['o.create_time', '>=', strtotime($input['start'])],
                ['o.create_time', '<=', strtotime($input['end'])],
            ];

            $table = Db::table('eb_order')->alias('o');
            switch ($adminInfo['type']) {
                case 1: // 超管
                    if ($input['type'] ==1) {
                        // 超管给运营商直接划账
                        $map[] = ['o.company_status', '=', 0];
                        $map[] = ['o.operate_id', 'in', $input['data']];
                        $update = ['o.company_status' => 1];
                        $log['type'] = 1;
                        $field = 'count(*) as num,sum(total_price - company_price) as money,a.name as desc_name';
                        $logInfo = $table->leftJoin(['eb_admin' => 'a'], 'a.id = o.operate_id')
                            ->field($field)->where($map)->group('o.operate_id')->select()->toArray();
                        if (!$logInfo) return jsonFail('获取数据失败');
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                case 2: // 运营方
                    $map[] = ['o.company_status', '=', 1];
                    $map[] = ['o.operate_id', '=', $adminInfo['id']];
                    if ($input['type'] == 2 ) {
                        $map[] = ['o.operate_status', '=', 0];
                        $map[] = ['o.store_id', 'in', $input['data']];
                        $update = ['o.operate_status' => 1];
                        $log['type'] = 2;
                        $field = 'count(*) as num,sum(store_price) as money, s.shop_name as desc_name';
                        $logInfo = $table->leftJoin(['eb_store' => 's'], 's.id = o.store_id')
                            ->field($field)->where($map)->group('o.store_id')->select()->toArray();
                        if (!$logInfo) return jsonFail('获取数据失败');
                    }elseif($input['type'] == 3) {
                        $map[] = ['o.send_status', '=', 0];
                        $map[] = ['o.send_id', 'in', $input['data']];
                        $update = ['o.send_status' => 1];
                        $log['type'] = 3;
                        $field = 'count(*) as num,sum(floor_price) as money, u.name as desc_name , u.phone';
                        $logInfo = $table->leftJoin(['eb_user' => 'u'], 'u.id = o.send_id')
                            ->field($field)->where($map)->group('o.send_id')->select()->toArray();
                        if (!$logInfo) return jsonFail('获取数据失败');
                        $logInfo = array_map(function ($v){
                            $v['desc_name'] .= '-' . $v['phone'];
                            unset($v['phone']);
                            return $v;
                        },$logInfo);
                    } elseif($input['type'] == 4) {
                        $map[] = ['o.dor_manager_status', '=', 0];
                        $map[] = ['o.manag_id', 'in', $input['data']];
                        $update = ['o.dor_manager_status' => 1];
                        $log['type'] = 4;
                        $field = 'count(*) as num, sr.name as desc_name , sr.phone,sum(s.dor_manager_price) as money';
                        $logInfo = $table->leftJoin(['eb_school_role' => 'sr'], 'sr.id = o.manag_id')
                            ->leftJoin(['eb_school' => 's'], 's.id = o.school_id')
                            ->field($field)->where($map)->group('o.manag_id')->select()->toArray();
                        if (!$logInfo) return jsonFail('获取数据失败');
                        $logInfo = array_map(function ($v){
                            $v['desc_name'] .= '-' . $v['phone'];
                            unset($v['phone']);
                            return $v;
                        },$logInfo);
                    } elseif($input['type'] == 5) {
                        $map[] = ['o.box_status', '=', 0];
                        $map[] = ['o.Boxing_id', 'in', $input['data']];
                        $update = ['o.box_status' => 1];
                        $log['type'] = 5;
                        $field = 'count(*) as num, sr.name as desc_name , sr.phone,sum(s.box_price) as money';
                        $logInfo = $table->leftJoin(['eb_school_role' => 'sr'], 'sr.id = o.Boxing_id')
                            ->leftJoin(['eb_school' => 's'], 's.id = o.school_id')
                            ->field($field)->where($map)->group('o.Boxing_id')->select()->toArray();
                        if (!$logInfo) return jsonFail('获取数据失败');
                        $logInfo = array_map(function ($v){
                            $v['desc_name'] .= '-' . $v['phone'];
                            unset($v['phone']);
                            return $v;
                        },$logInfo);
                    } else {
                        return jsonFail('非法数据');
                    }
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            Db::startTrans();
            $rtn1 = $table->where($map)->update($update);
            foreach ($logInfo as &$v) {
                $v = array_merge($v, $log);
            }
            $rtn2 = Db::table('eb_draw_log')->insertAll($logInfo);
            if ($rtn1  && $rtn2 == count($logInfo)) {
                Db::commit();
                return jsonSuccess('划账成功');
            }
            Db::rollback();
            return jsonFail('划账失败,刷新页面重试');
        } catch (E $e) {
            var_dump($e->getMessage());
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**划账记录列表
     * @param Request $request
     * @return Json
     */
    public function logList(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['page'] = $request->post('page');//
            $input['limit'] = $request->post('limit');//
            $input['type'] = $request->post('type');//
            // 参数校验
            $validate = Validate::rule([
                'page' => ValidateRule::isRequire(null, '缺少参数'),
                'limit' => ValidateRule::isRequire(null, '缺少参数'),
                'type' => function($v) {
                    if ($v === null) {
                        return '缺少参数';
                    } else if (in_array($v, ['1', '2', '3','4','5'], true)) {
                        return true;
                    } else {
                        return '不合法的参数';
                    }
                }
            ]);
            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1],[1,2,3,4]);
            if ($adminInfo instanceof Json) return $adminInfo;
            if ($adminInfo['type'] == 1 || $adminInfo['type'] == 2) {
                $map[] = ['operate_id|pid', '=', $adminInfo['id']];
                if ($adminInfo['type'] == 1) {
                    $map[] = ['type', '=', 1];
                } else {
                  if (in_array($input['type'], ['2', '3','4','5'])) {
                      $map[] = ['type', '=', $input['type']];
                  } else {
                      return jsonFail('不合法的参数1');
                  }
                }
            } else if ($adminInfo['type'] == 3 || $adminInfo['type'] == 4) {
                $map[] = ['operate_id', '=', $adminInfo['id']];
                if ($adminInfo['type'] == 3) {
                    $map[] = ['type', '=', 1];
                } else {
                    if (in_array($input['type'], ['2', '3','4','5'])) {
                        $map[] = ['type', '=', $input['type']];
                    } else {
                        return jsonFail('不合法的参数2');
                    }
                }
            }
            $table = Db::table('eb_draw_log')->field('id,name,desc_name,money,num,draw_time,type,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time')->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('查询成功', ['count' => 0, 'list' => []]);
            $list = $table->order('create_time', 'desc')->page($input['page'], $input['limit'])->select()->toArray();
            return jsonSuccess('查询成功', ['count' => $count, 'list' => $list]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除划账记录
     * @param Request $request
     * @return Json
     */
    public function delLog(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['type'] = $request->post('type');//
            $input['ids'] = $request->post('ids');//
//            var_dump($input);
            // 参数校验
            $validate = Validate::rule([
                'ids' => function($v) {
                    if ($v === null) {
                        return '缺少参数';
                    } else if (is_array($v)) {
                        return true;
                    } else {
                        return '不合法的参数';
                    }
                },
                'type' => function($v) {
                    if ($v === null) {
                        return '缺少参数';
                    } else if (in_array($v, ['1', '2', '3'], true)) {
                        return true;
                    } else {
                        return '不合法的参数';
                    }
                }
            ]);
            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1],[1,2,3,4]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [
              ['type', '=', $input['type']],
              ['id', 'in', $input['ids']]
            ];
            $rtn = Db::table('eb_draw_log')->where($map)->delete();
            if ($rtn) return jsonSuccess('删除成功');
            return jsonFail('删除失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }
}
